<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <h2>动态组件</h2>
      <button @click="str = 'child1'">btn1</button>
      <button @click="str = 'child2'">btn2</button>
      <button @click="str = 'child3'">btn3</button>
      <!-- <child1 v-if="count === 1"></child1>
      <child2 v-if="count === 2"></child2>
      <child3 v-if="count === 3"></child3> -->

      <!-- 动态组件component,一定要配合is属性，写字符串，对应组件名称 -->
      <!-- 用component标签绑定的组件，在切走的时候是会被卸载的 -->

      <!-- keep-alive表示缓存组件，当组件切走的时候，不会被销毁，不会重新创建，保留之前的状态 -->
      <keep-alive>
        <component :is="str"></component>
      </keep-alive>
    </div>

    <script src="./Vue3.js"></script>
    <script>
      const { createApp } = Vue;

      let timer;
      const Child1 = {
        data() {
          return {
            count: 1,
          };
        },
        template: `
          <div>child1组件 - {{ count }}</div>
        `,
        mounted() {
          console.log("child1组件被重新渲染了");
          // setInterval(() => {
          //   // console.log(1111);
          //   this.count++;
          // }, 1000);
        },
        beforeUnmount() {
          console.log("child1组件被卸载了");
        },
        // 当缓存的组件被激活时调用
        activated() {
          // console.log(1);
          timer = setInterval(() => {
            // console.log(1111);
            this.count++;
          }, 1000);
        },
        // 当缓存的组件被失活时调用
        deactivated() {
          console.log(2);
          clearInterval(timer);
        },
      };
      const Child2 = {
        template: `
          <div>child2组件</div>
        `,
      };
      const Child3 = {
        template: `
          <div>child3组件</div>
        `,
      };

      createApp({
        data() {
          return {
            // count: 1,
            str: "child1",
          };
        },
        components: {
          Child1,
          Child2,
          Child3,
        },
      }).mount("#app");
    </script>
  </body>
</html>
